﻿/******************************************************   
创建者: ljj
创建时间: 2018-09-10
修改:
修改时间: 
功能: 订货会
 ******************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.kmer;
using com.kmer.ApiServer;
using com.kmer.ApiServer.Attributes;
using com.kmer.Attributes;
using com.kmer.db;
using com.kmer.Helper;
using kmer.Data;
using Nancy.Extensions;
using WxNewOrderAPI.model;
using System.Net;

namespace WxNewOrderAPI
{
    public class WXNewOrderHandler : WXBaseHandler
    {
        /// <summary>
        /// 正在执行的订货会
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        /// writer:ljj
        /// Create Date：2018-09-10
        public IList<NewOrderModel.OrderMasterModel> GetGoingOrder(km_platformEntities dc)
        {
            var result = (from a in dc.t_order_new_master
                join b in dc.t_order_new_styledetail
                on a.MasterID equals b.MasterID
                where a.OrderFlag == false && a.BeginDate <= DateTime.Now && a.EndDate >= DateTime.Now
                group b by new {a.MasterID, a.OrderName, a.AliasName, a.BeginDate, a.EndDate}
                into u
                select new NewOrderModel.OrderMasterModel
                {
                    MasterID = u.Key.MasterID,
                    OrderName = u.Key.AliasName ?? u.Key.OrderName,
                    BeginDate = u.Key.BeginDate,
                    EndDate = u.Key.EndDate
                }).OrderBy(d => d.MasterID).ToList();
            return result;
        }

        /// <summary>
        /// 订货会总数
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        public int GetAllOrder(km_platformEntities dc)
        {
            var result = dc.t_order_new_master.Count(d => d.OrderFlag != true);
            return result;
        }

        /// <summary>
        /// 参与订货会数
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="OpenID"></param>
        /// <returns></returns>
        public int GetToPart(km_platformEntities dc,string OpenID)
        {
            var result = (from m in dc.t_order_new_master
                join grm in dc.t_order_new_GradeResult_Mater
                on m.MasterID equals grm.MasterID
                where grm.OpenId == OpenID && m.OrderFlag != true
                select m).Distinct().Count();
            return result;
        }
        
        /// writer:ljj
        /// Create Date：2018-09-10
        [Description("条件")]
        [ReturnType(typeof(IList<NewOrderModel.BigKindModel>))]
        public ApiResult GetBigKind([ParamDescription("订货会ID")] int? MasterID = null)
        {
            try
            {
                if (!MasterID.HasValue) return Error("订货会内码ID不能为空!");
                var dc = new km_platformEntities();
                var query = (from sd in dc.t_order_new_styledetail
                    where sd.MasterID == MasterID
                    select sd.BigKind).DistinctBy(d => d).Select(
                    d => new NewOrderModel.BigKindModel
                    {
                        BigKind = d
                    }).ToList();
                return Success(query);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }
        
        /// writer:ljj
        /// Create Date：2018-09-10
        [Description("条件")]
        [ReturnType(typeof(IList<NewOrderModel.ConcditionModel>))]
        public ApiResult GetCondition([ParamDescription("订货会ID")] int? MasterID = null)
        {
            try
            {
                if (!MasterID.HasValue) return Error("订货会内码ID不能为空!");
                var dc = new km_platformEntities();
                var query = (from sd in dc.t_order_new_styledetail
                        where sd.MasterID == MasterID
                        select new {sd.SerialName, sd.ModelName}).AsEnumerable().DistinctBy(d => new {d.SerialName, d.ModelName })
                    .GroupBy(d => d.SerialName).Select(
                        d => new NewOrderModel.ConcditionModel
                        {
                            SerialName = d.Key,
                            itemList = d.Select(r => new NewOrderModel.ItemModel
                            {
                                ItemName = r.ModelName
                            }).ToList()
                        }).ToList();
                return Success(query);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }

        /// writer:ljj
        /// Create Date：2018-09-10
        [Description("商品列表")]
        [ReturnType(typeof(PaperData<NewOrderModel.GoodCoreModel>))]
        public ApiResult GetGoodList([ParamDescription("订货会ID")] int? MasterID = null,
            [ParamDescription("OpenId")] string OpenId = "", [ParamDescription("大类")] string BigKind = "",
            [ParamDescription("系列")] string SerialName = "", [ParamDescription("项目")] string ItemName = "",
            [ParamDescription("流水号")] string SerialNo = "",
            [ParamDescription("是否评分：null=全部 true=已评 false=未评")] bool? IsScore = null,
            [ParamDescription("页码")] int Page = 1, [ParamDescription("页数")] int Size = 20)
        {
            try
            {
                if (!MasterID.HasValue) return Error("订货会内码ID不能为空!");
                if (string.IsNullOrEmpty(OpenId)) return Error("OpenID不能为空!");
                var companyID = this.CompanyID;
                var dc = new km_platformEntities();
                var query = from sd in dc.t_order_new_styledetail
                    join m in dc.t_order_new_master
                    on new {sd.MasterID, sd.CompanyID} equals new {m.MasterID, m.CompanyID}
                    where sd.MasterID == MasterID && sd.CompanyID == companyID && m.MasterID == MasterID &&
                          m.CompanyID == companyID
                    join grm in (from ogrm in dc.t_order_new_GradeResult_Mater
                        where ogrm.CompanyID == companyID && ogrm.OpenId == OpenId
                        select ogrm)
                    on new {sd.MasterID, sd.CompanyID, sd.SerialNo} equals new
                    {
                        grm.MasterID,
                        grm.CompanyID,
                        grm.SerialNo
                    }
                    into temp
                    from tt in temp.DefaultIfEmpty()
                    select new
                    {
                        sd.DetailID,
                        sd.MasterID,
                        sd.SerialNo,
                        sd.DesignNo,
                        sd.BigKind,
                        sd.SerialName,
                        sd.ItemName,sd.ModelName,
                        sd.MaterialProperty,
                        sd.RetailPrice,
                        m.OrderName,
                        tt
                    };
                if (!string.IsNullOrEmpty(BigKind))
                {
                    query = query.Where(d => d.BigKind == BigKind);
                }
                if (!string.IsNullOrEmpty(SerialName))
                {
                    query = query.Where(d => d.SerialName == SerialName);
                }
                if (!string.IsNullOrEmpty(ItemName))
                {
                    var itemList = ItemName.Split(',');
                    query = query.Where(d => itemList.Contains(d.ModelName));
                }
                if (IsScore.HasValue)
                {
                    if (IsScore.Value)
                    {
                        query = query.Where(d => d.tt != null);
                    }
                    else
                    {
                        query = query.Where(d => d.tt == null);
                    }
                }
                if (!string.IsNullOrEmpty(SerialNo))
                {
                    query = query.Where(d => d.SerialNo.Contains(SerialNo));
                }
                query = query.OrderBy(d => d.DetailID);
                var result = PaperData<NewOrderModel.GoodCoreModel>.Create(query.Count(), Size, Page);
                result.Items = query.Skip(result.Skip).Take(result.Limt).ToList().Select(
                    d => new NewOrderModel.GoodCoreModel
                    {
                        DetailID = d.DetailID,
                        MasterID = d.MasterID,
                        SerialNo = d.SerialNo,
                        DesignNo = d.DesignNo,
                        SerialName = d.SerialName,
                        ItemName = d.ItemName,
                        MaterialProperty = d.MaterialProperty,
                        RetailPrice = d.RetailPrice,
                        ImgUrl = d.SerialNo == null
                            ? "http://tsf.erp-km.cn:9005/assets/weixin/upload.png"
                            : GetWXImageUrlV3(dc, d.MasterID, d.SerialNo),
                        IsScore = d.tt != null
                    }).ToList();
                return Success(result);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }

        /// writer:ljj
        /// Create Date：2018-09-10
        [Description("商品详情")]
        [ReturnType(typeof(NewOrderModel.GoodShowModel))]
        public ApiResult GetGoodDetail([ParamDescription("订货会内码ID")] int? MasterID = null,
            [ParamDescription("商品内码ID")] int? DetailID = null, [ParamDescription("OpenId")] string OpenId = "",
            [ParamDescription("条数")] int Size = 10)
        {
            try
            {
                if (!MasterID.HasValue) return Error("订货会内码ID不能为空!");
                if (!DetailID.HasValue) return Error("商品内码ID不能为空!");
                var companyID = this.CompanyID;
                var dc = new km_platformEntities();
                var goodInfo = GetGoodInfo(dc, MasterID.Value, DetailID.Value, companyID, OpenId);
                var scoreList = GetScoreList(dc, MasterID.Value, goodInfo?.SerialNo, companyID, OpenId);
                var similar = GetSimilar(dc, MasterID.Value, companyID, goodInfo?.DesignNo, goodInfo?.BigKind,
                    goodInfo?.SerialName, goodInfo?.ItemName, OpenId, Size);
                var sameGoodList = GetSameDesignNo(dc, MasterID.Value, goodInfo?.DesignNo, companyID, OpenId);
                var result = new NewOrderModel.GoodShowModel
                {
                    goodInfo = goodInfo,
                    scoreList = scoreList,
                    similarList = similar,
                    sameGoodList = sameGoodList
                };
                return Success(result);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error(ex);
            }
        }

        /// <summary>
        /// 同款
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="MasterID"></param>
        /// <param name="DesignNo"></param>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        /// writer:ljj
        /// Create Date：2018-07-21
        public IList<NewOrderModel.SameGoodModel> GetSameDesignNo(km_platformEntities dc, int MasterID, string DesignNo,
            string CompanyID, string OpenId)
        {
            try
            {
                var query = (from sd in dc.t_order_new_styledetail
                    join m in dc.t_order_new_master
                    on new {sd.MasterID, sd.CompanyID} equals new {m.MasterID, m.CompanyID}
                    where sd.MasterID == MasterID && sd.CompanyID == CompanyID && m.MasterID == MasterID &&
                          m.CompanyID == CompanyID && sd.DesignNo == DesignNo
                    join grm in (from ogrm in dc.t_order_new_GradeResult_Mater
                        where ogrm.CompanyID == CompanyID && ogrm.OpenId == OpenId && ogrm.MasterID == MasterID
                        select ogrm)
                    on new {sd.MasterID, sd.CompanyID, sd.SerialNo} equals new
                    {
                        grm.MasterID,
                        grm.CompanyID,
                        grm.SerialNo
                    }
                    into temp
                    from tt in temp.DefaultIfEmpty()
                    select new
                    {
                        sd.MasterID,
                        sd.DetailID,
                        sd.DesignNo,
                        sd.SerialNo,
                        IsScore = tt != null
                    }).ToList();
                var result = query.Select(d => new NewOrderModel.SameGoodModel
                {
                    MasterID = d.MasterID,
                    DetailID = d.DetailID,
                    DesignNo = d.DesignNo,
                    SerialNo = d.SerialNo,
                    ImgUrl = d.SerialNo == null
                        ? "http://tsf.erp-km.cn:9005/assets/weixin/upload.png"
                        : GetWXImageUrlV3(dc, d.MasterID, d.SerialNo),
                    IsScore = d.IsScore
                });
                return result.ToList();
            }
            catch (Exception ex)
            {
                throw(ex);
            }
        }

        /// <summary>
        /// 商品信息
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="MasterID"></param>
        /// <param name="DetailID"></param>
        /// <param name="CompanyID"></param>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        /// writer:ljj
        /// Create Date：2018-09-10
        public NewOrderModel.GoodInfoModel GetGoodInfo(km_platformEntities dc, int MasterID, int DetailID,
            string CompanyID, string OpenId)
        {
            try
            {
                var query = (from sd in dc.t_order_new_styledetail
                    join m in dc.t_order_new_master
                    on new {sd.MasterID, sd.CompanyID} equals new {m.MasterID, m.CompanyID}
                    where sd.MasterID == MasterID && sd.CompanyID == CompanyID && m.MasterID == MasterID &&
                          m.CompanyID == CompanyID && sd.DetailID == DetailID
                    join grm in (from ogrm in dc.t_order_new_GradeResult_Mater
                        where ogrm.CompanyID == CompanyID && ogrm.OpenId == OpenId && ogrm.MasterID == MasterID
                        select ogrm)
                    on new {sd.MasterID, sd.CompanyID, sd.SerialNo} equals new
                    {
                        grm.MasterID,
                        grm.CompanyID,
                        grm.SerialNo
                    }
                    into temp
                    from tt in temp.DefaultIfEmpty()
                    select new NewOrderModel.GoodInfoModel
                    {
                        DetailID = sd.DetailID,
                        MasterID = sd.MasterID,
                        SerialNo = sd.SerialNo,
                        DesignNo = sd.DesignNo,
                        ColorName = sd.ColorName,
                        YearNo = sd.YearNo,
                        SeasonName = sd.SeasonName,
                        BigKind = sd.BigKind,
                        SerialName = sd.SerialName,
                        MaterialProperty = sd.MaterialProperty,
                        ItemName = sd.ItemName,
                        ModelName = sd.ModelName,
                        ThicknessName = sd.ThicknessName,
                        ElementName = sd.ElementName,
                        CollarTypeName = sd.CollarTypeName,
                        ClothesVersionName = sd.ClothesVersionName,
                        CommodityProfileName = sd.CommodityProfileName,
                        DesignName = sd.DesignName,
                        StuffName = sd.StuffName,
                        Lining = sd.Lining,
                        VendCustName = sd.VendCustName,
                        RetailPrice = sd.RetailPrice,
                        CostPrice = sd.CostPrice,
                        OrderRate = sd.OrderRate,
                        IsScore = tt != null,
                    }).FirstOrDefault();
                if (query != null)
                {
                    query.ImgUrl = query.SerialNo == null
                        ? "http://tsf.erp-km.cn:9005/assets/weixin/upload.png"
                        : GetWXImageUrlV3(dc, query.MasterID, query.SerialNo);
                }
                return query;
            }
            catch (Exception ex)
            {
                throw(ex);
            }
        }

        /// <summary>
        /// 评分
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="MasterID"></param>
        /// <param name="SerialNo"></param>
        /// <param name="CompanyID"></param>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        /// writer:ljj
        /// Create Date：2018-09-10
        public IList<NewOrderModel.ScoreItemModel> GetScoreList(km_platformEntities dc, int MasterID, string SerialNo,
            string CompanyID, string OpenId)
        {
            try
            {
                var scoreItem = (from p in dc.sys_dictionary
                    join c in dc.sys_dictionary
                    on p.ID equals c.ParentId
                    where p.dictValue == "newgoods" && !p.isRemove && !c.isRemove
                                 select new
                    {
                        c.dictName,
                        c.dictValue
                    }).ToList();
                var scoreValue = (from p in dc.sys_dictionary
                    join c in dc.sys_dictionary
                    on p.ID equals c.ParentId
                    where p.dictName == "新项目评分值" && !p.isRemove && !c.isRemove
                    select new NewOrderModel.ScoreValueModel
                    {
                        ScoreValue = c.dictValue
                    }).ToList();
                var score = (from m in dc.t_order_new_GradeResult_Mater
                    join d in dc.t_order_new_GradeResult_Detail
                    on m.ResultID equals d.ResultID
                    where m.MasterID == MasterID && m.SerialNo == SerialNo && m.OpenId == OpenId &&
                          m.CompanyID == CompanyID
                    select new
                    {
                        m.ResultID,
                        d.AStoreRating,
                        d.BStoreRating,
                        d.StyleRating
                    }).FirstOrDefault();
                var result = new List<NewOrderModel.ScoreItemModel>();
                foreach (var item in scoreItem)
                {
                    var newItem = new NewOrderModel.ScoreItemModel
                    {
                        ScoreItem = item.dictName,
                        scoreValueList = scoreValue,
                    };
                    switch (item.dictValue)
                    {
                        case "A":
                            newItem.Score = score?.AStoreRating;
                            break;
                        case "B":
                            newItem.Score = score?.BStoreRating;
                            break;
                        case "C":
                            newItem.Score = score?.StyleRating;
                            break;
                        default: break;
                    }
                    result.Add(newItem);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw(ex);
            }
        }

        /// <summary>
        /// 找相似
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="MasterID"></param>
        /// <param name="CompanyID"></param>
        /// <param name="SerialNo"></param>
        /// <param name="SeriesName"></param>
        /// <param name="ItemName"></param>
        /// <returns></returns>
        /// writer:ljj
        /// Create Date：2018-09-10
        public IList<NewOrderModel.GoodNeceModel> GetSimilar(km_platformEntities dc, int MasterID, string CompanyID,
            string DesignNo, string BigKind, string SeriesName, string ItemName, string OpenId, int Size)
        {
            try
            {
                var list = (from sd in dc.t_order_new_styledetail
                    join m in dc.t_order_new_master
                    on new {sd.MasterID, sd.CompanyID} equals new {m.MasterID, m.CompanyID}
                    where sd.MasterID == MasterID && sd.CompanyID == this.CompanyID && sd.DesignNo != DesignNo &&
                          sd.BigKind.Contains(BigKind) && sd.SerialName.Contains(SeriesName) &&
                          sd.ItemName.Contains(ItemName) && m.MasterID == MasterID && m.CompanyID == CompanyID
                    join grm in (from ogrm in dc.t_order_new_GradeResult_Mater
                        where ogrm.CompanyID == CompanyID && ogrm.OpenId == OpenId && ogrm.MasterID == MasterID
                        select ogrm)
                    on new {sd.MasterID, sd.CompanyID, sd.SerialNo} equals new
                    {
                        grm.MasterID,
                        grm.CompanyID,
                        grm.SerialNo
                    }
                    into temp
                    from tt in temp.DefaultIfEmpty()
                    select new
                    {
                        sd.DetailID,
                        sd.MasterID,
                        sd.SerialNo,
                        sd.DesignNo,
                        sd.BigKind,
                        sd.SerialName,
                        sd.ItemName,
                        sd.RetailPrice,
                        m.OrderName,
                        tt
                    }).OrderBy(t => t.DetailID).Take(Size).ToList().Select(d => new NewOrderModel.GoodNeceModel
                {
                    DetailID = d.DetailID,
                    MasterID = d.MasterID,
                    SerialNo = d.SerialNo,
                    BigKind = d.BigKind,
                    SerialName = d.SerialName,
                    ItemName = d.ItemName,
                    RetailPrice = d.RetailPrice,
                    ImgUrl = d.SerialNo == null
                        ? "http://tsf.erp-km.cn:9005/assets/weixin/upload.png"
                        : GetWXImageUrlV3(dc, d.MasterID, d.SerialNo),
                    IsScore = d.tt != null
                }).ToList();
                return list;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// writer：ljj
        /// date：2018-09-10
        [Description("保存评分数据")]
        [JsonType]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SaveGrade([ParamDescription("参数实体类")] NewOrderModel.ScoreSaveModel param)
        {
            if (param == null) return Error("参数对象为空!");
            var dc = new km_platformEntities();
            using (var tran = dc.Database.BeginTransaction())
            {
                try
                {
                    if (string.IsNullOrEmpty(param.OpenId)) return Error("OpenID不能为空!");
                    var companyID = this.CompanyID;
                    var user = dc.t_order_new_wx_account.FirstOrDefault(
                        d => d.OpenId == param.OpenId && !d.IsDisable && !d.IsRemove &&
                             (d.AccountType == 0 || d.AccountType == 2 || d.AccountType == 3));
                    if (user == null) return Error("该用户没有权限!");
                    var detail = (from sd in dc.t_order_new_styledetail
                        join m in dc.t_order_new_master
                        on new {sd.CompanyID, sd.MasterID} equals new {m.CompanyID, m.MasterID}
                        where sd.MasterID == param.MasterID && sd.DetailID == param.DetailID &&
                              sd.CompanyID == companyID &&
                              m.MasterID == param.MasterID && m.CompanyID == companyID
                        select sd).FirstOrDefault();
                    if (detail != null)
                    {
                        var mater =
                            dc.t_order_new_GradeResult_Mater.FirstOrDefault(
                                d => d.CompanyID == companyID && d.MasterID == param.MasterID &&
                                     d.SerialNo == detail.SerialNo && d.OpenId == param.OpenId);
                        if (mater != null)
                        {
                            var score = dc.t_order_new_GradeResult_Detail.FirstOrDefault(d => d.ResultID == mater.ResultID);
                            if (score != null)
                            {
                                score.AStoreRating = param.AStoreRating;
                                score.BStoreRating = param.BStoreRating;
                                score.StyleRating = param.StyleRating;
                            }
                            else
                            {
                                var newScore = new t_order_new_GradeResult_Detail
                                {
                                    ResultID = mater.ResultID,
                                    AStoreRating = param.AStoreRating,
                                    BStoreRating = param.BStoreRating,
                                    StyleRating = param.StyleRating,
                                };
                                dc.t_order_new_GradeResult_Detail.Add(newScore);
                            }
                        }
                        else
                        {
                            var newMater = new t_order_new_GradeResult_Mater
                            {
                                MasterID = param.MasterID,
                                CompanyID = companyID,
                                ExtrSource = companyID,
                                SerialNo = detail.SerialNo,
                                PersonalScore = 0M,
                                GradeTime = DateTime.Now,
                                OpenId = param.OpenId,
                            };
                            dc.t_order_new_GradeResult_Mater.Add(newMater);
                            dc.SaveChanges();
                            var score = dc.t_order_new_GradeResult_Detail.FirstOrDefault(d => d.ResultID == newMater.ResultID);
                            if (score != null)
                            {
                                score.AStoreRating = param.AStoreRating;
                                score.BStoreRating = param.BStoreRating;
                                score.StyleRating = param.StyleRating;
                            }
                            else
                            {
                                var newScore = new t_order_new_GradeResult_Detail
                                {
                                    ResultID = newMater.ResultID,
                                    AStoreRating = param.AStoreRating,
                                    BStoreRating = param.BStoreRating,
                                    StyleRating = param.StyleRating,
                                };
                                dc.t_order_new_GradeResult_Detail.Add(newScore);
                            }
                        }
                        dc.SaveChanges();
                        tran.Commit();
                    }
                    return Success(0);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Log.Error(ex);
                    return Error(ex);
                }
            }
        }

        /// <summary>
        /// 获取待审商品列表V2 api 中的图片地址
        /// </summary>
        /// <param name="request"></param>
        /// <param name="MasterID">订货会ID</param>
        /// <param name="SerialNo">流水号</param>
        /// <returns></returns>
        private string GetWXImageUrlV3(km_platformEntities dc, int MasterID, string SerialNo)
        {
            var query = dc.kmImages.FirstOrDefault(d => d.Title == (MasterID + "/" + SerialNo));
            if (query != null)
            {
                var url = $"http://kmer-online-pic.oss-cn-shenzhen.aliyuncs.com/NewOrderApp/{MasterID}/{SerialNo}.jpg";
                if (RemoteFileExists(url))
                {
                    return url;
                }
            }
            return "http://tsf.erp-km.cn:9005/assets/weixin/upload.png";
        }

        private bool RemoteFileExists(string fileUrl)
        {
            bool result = false;//下载结果

            WebResponse response = null;
            try
            {
                WebRequest req = WebRequest.Create(fileUrl);

                response = req.GetResponse();

                result = response == null ? false : true;

            }
            catch (Exception ex)
            {
                result = false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return result;
        }
    }
}
